package com.ovopark.organize.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.ovopark.organize.server.mapper.FranchiseesApprovalAddressMapper;
import com.ovopark.organize.server.model.entity.FranchiseesAccurateAddress;
import com.ovopark.organize.server.model.entity.FranchiseesApprovalAddress;
import com.ovopark.organize.server.model.entity.FranchiseesApprovalAddressRegistration;
import com.ovopark.organize.server.model.entity.FranchiseesRegistration;
import com.ovopark.organize.server.model.query.FranchiseesApprovalAddressQuery;
import com.ovopark.organize.server.service.FranchiseesAccurateAddressService;
import com.ovopark.organize.server.service.FranchiseesApprovalAddressRegistrationService;
import com.ovopark.organize.server.service.FranchiseesApprovalAddressService;
import com.ovopark.organize.server.service.FranchiseesRegistrationService;
import com.ovopark.organize.server.util.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description: 选址点位
 * @param:
 * @return:
 * @author wxb
 * @date: 2024/6/4 10:06
 */
@Service
@Slf4j
public class FranchiseesApprovalAddressServiceImpl extends ServiceImpl<FranchiseesApprovalAddressMapper, FranchiseesApprovalAddress> implements FranchiseesApprovalAddressService {

    @Resource
    private FranchiseesApprovalAddressRegistrationService franchiseesApprovalAddressRegistrationService;

    @Resource
    private FranchiseesRegistrationService franchiseesRegistrationService;

    @Resource
    private FranchiseesAccurateAddressService franchiseesAccurateAddressService;
    /** 
     * @description: 新增点位
     * @param: [address]
     * @return: com.ovopark.organize.server.model.entity.FranchiseesApprovalAddress
     * @author wxb
     * @date: 2024/6/4 10:25
     */ 
    @Override
    public FranchiseesApprovalAddress saveOrUpdateAddress(FranchiseesApprovalAddress address) {
        if (address.getId() != null) {
            baseMapper.updateById(address);
        } else {
            baseMapper.insert(address);
            if (address.getRegistrationId() != null) {
                // 绑定线索
                this.addRegistration(address.getGroupId(), address.getId(), address.getRegistrationId(), address.getUpdateId());
            }
        }
        return address;
    }

    /** 
     * @description: 分页查询
     * @param: [page, groupId, query]
     * @return: java.util.List<com.ovopark.organize.server.model.entity.FranchiseesApprovalAddress>
     * @author wxb
     * @date: 2024/6/4 10:25
     */ 
    @Override
    public IPage<FranchiseesApprovalAddress> page(Page<FranchiseesApprovalAddress> page, Integer groupId, FranchiseesApprovalAddressQuery query) {
        // 分页查询
        IPage<FranchiseesApprovalAddress> iPage = baseMapper.getPage(page, groupId, query);
        List<FranchiseesApprovalAddress> list = iPage.getRecords();
        // 查询客户
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(address -> {
                List<FranchiseesRegistration> registrationList = this.getByAddressId(groupId, address.getId());
                address.setRegistrationList(registrationList);
            });
            iPage.setRecords(list);
        }
        return iPage;

    }

    /** 
     * @description: 查看点位
     * @param: [id]
     * @return: com.ovopark.organize.server.model.entity.FranchiseesApprovalAddress
     * @author wxb
     * @date: 2024/6/4 10:50
     */ 
    @Override
    public FranchiseesApprovalAddress getById(Integer id) {
        return this.baseMapper.selectById(id);
    }

    /**
     * @description: 根据点位获取线索 分页
     * @param: [page, groupId, addressId]
     * @return: com.baomidou.mybatisplus.core.metadata.IPage<com.ovopark.organize.server.model.entity.FranchiseesRegistration>
     * @author wxb
     * @date: 2024/6/4 16:12
     */
    @Override
    public IPage<FranchiseesRegistration> getPageByAddressId(Page<FranchiseesRegistration> page, Integer groupId, Integer addressId) {
        if (addressId != null) {
            IPage<FranchiseesRegistration> iPage = baseMapper.getPageByAddressId(page, groupId, addressId);
            if(CollectionUtil.isNotEmpty(iPage.getRecords())){
                List<FranchiseesRegistration> list = iPage.getRecords();
                List<Integer> franchiseesRegistrationIds = list.stream().filter(o->o.getUserId() ==null).map(FranchiseesRegistration::getId).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(franchiseesRegistrationIds)){
                    Map<Integer,FranchiseesAccurateAddress> accurateAddressMap = franchiseesAccurateAddressService.getFranchiseesAccurateAddressUserByRegistrationIds(franchiseesRegistrationIds,groupId,addressId);
                  if(CollectionUtil.isNotEmpty(accurateAddressMap)){
                      list.forEach(registration -> {
                          if(registration.getUserId() ==null && franchiseesRegistrationIds.contains(registration.getId())){
                              FranchiseesAccurateAddress accurateAddress = accurateAddressMap.get(registration.getId());
                              if(accurateAddress != null){
                                  registration.setUserId(accurateAddress.getUserId());
                              }

                          }
                      });

                      iPage.setRecords(list);
                  }

                }

            }

            return iPage;
        }
        return null;
    }

    /**
     * @description: 根据点位获取线索
     * @param: [groupId, addressId]
     * @return: java.util.List<com.ovopark.organize.server.model.entity.FranchiseesRegistration>
     * @author wxb
     * @date: 2024/6/5 16:20
     */
    @Override
    public List<FranchiseesRegistration> getByAddressId(Integer groupId, Integer addressId) {
        if (addressId != null) {
            return baseMapper.getByAddressId(groupId, addressId);
        }
        return Lists.newArrayList();
    }

    /**
     * @description: 线索下的点位
     * @param: [registrationId, groupId]
     * @return: java.util.List<com.ovopark.organize.server.model.entity.FranchiseesApprovalAddress>
     * @author wxb
     * @date: 2024/6/6 16:32
     */
    @Override
    public List<FranchiseesApprovalAddress> getByRegistrationId(Integer registrationId, Integer groupId) {
        if (registrationId != null) {
            return baseMapper.getByRegistrationId(registrationId, groupId);
        }
        return Lists.newArrayList();
    }

    /**
     * @description: 批量删除
     * @param: [idList]
     * @return: void
     * @author wxb
     * @date: 2024/6/11 18:27
     */
    @Override
    public void batchDeleteAddress(List<Integer> idList) {
        if (CollectionUtil.isNotEmpty(idList)) {
            LambdaQueryWrapper<FranchiseesApprovalAddress> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(FranchiseesApprovalAddress::getId, idList);
            FranchiseesApprovalAddress franchiseesApprovalAddress = new FranchiseesApprovalAddress();
            franchiseesApprovalAddress.setIsDeleted(1);
            baseMapper.update(franchiseesApprovalAddress, queryWrapper);
        }
    }

    /**
     * @description: 删除点位
     * @param: [id]
     * @return: void
     * @author wxb
     * @date: 2024/6/11 18:27
     */
    @Override
    public void deleteAddress(Integer id) {
        if (id != null) {
            FranchiseesApprovalAddress franchiseesApprovalAddress = new FranchiseesApprovalAddress();
            franchiseesApprovalAddress.setId(id);
            franchiseesApprovalAddress.setIsDeleted(1);
            baseMapper.updateById(franchiseesApprovalAddress);
        }
    }

    /**
     * @description: 地址绑定线索
     * @param: [groupId, addressId, registrationId]
     * @return: com.ovopark.organize.server.model.entity.FranchiseesApprovalAddress
     * @author wxb
     * @date: 2024/6/11 18:35
     */
    @Override
    public void addRegistration(Integer groupId, Integer addressId, Integer registrationId, Integer userId) {
        // 查询线索
        FranchiseesRegistration registration = franchiseesRegistrationService.findFranchiseesRegistrationById(registrationId);
        if (registration != null) {
            FranchiseesApprovalAddressRegistration approvalAddressRegistration = franchiseesApprovalAddressRegistrationService.getBy(groupId, addressId, registrationId);
            if (approvalAddressRegistration != null) {
                approvalAddressRegistration.setUpdateTime(LocalDateTime.now());
                approvalAddressRegistration.setUpdateId(userId);
                franchiseesApprovalAddressRegistrationService.update(approvalAddressRegistration);
            } else {
                // 再新增
                if (franchiseesApprovalAddressRegistrationService.add(groupId, addressId, registrationId, userId)) {
                    registration.setPointNumber(registration.getPointNumber() + 1);
                    franchiseesRegistrationService.saveOrUpdateBean(registration);
                }
            }
        }
    }

    /**
     * @description: 移除线索
     * @param: [groupId, addressId, registrationId, userId]
     * @return: void
     * @author wxb
     * @date: 2024/6/12 10:12
     */
    @Override
    public void removeRegistration(Integer groupId, Integer addressId, Integer registrationId, Integer userId) {
        // 查询线索
        FranchiseesRegistration registration = franchiseesRegistrationService.findFranchiseesRegistrationById(registrationId);
        if (registration != null) {
            // 删除
            if (franchiseesApprovalAddressRegistrationService.deleteBy(groupId, addressId, registrationId)) {
                registration.setPointNumber(registration.getPointNumber() - 1);
                franchiseesRegistrationService.saveOrUpdateBean(registration);
            }
        }
    }

}
